package com.example.ssm1023.service.impl;

import com.example.ssm1023.config.AppResult;
import com.example.ssm1023.exception.ApplicationException;
import com.example.ssm1023.config.ResultCode;
import com.example.ssm1023.mapper.UserMapper;
import com.example.ssm1023.model.User;
import com.example.ssm1023.service.IUserService;
import com.example.ssm1023.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        //1.非空校验
        User dbUser = null;
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            log.error(ResultCode.FAIL_NULL_USERNAME_OR_PASSWORD.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAIL_NULL_USERNAME_OR_PASSWORD));
        }
        //2.校验是否正确
        dbUser = userMapper.selectUserByUserName(username);
        if(dbUser == null || !dbUser.getPassword().equals(password)) {
            //密码错误
            log.error(ResultCode.FAIL_ERROR_USERNAME_OR_PASSWORD.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAIL_ERROR_USERNAME_OR_PASSWORD));
        }
        //3.jwt 处理
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(username, token, 30, TimeUnit.SECONDS);//设置 30 分钟超时时间
        //3.校验通过，返回用户信息
        return dbUser;
    }

}
